package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    //保存用户资料
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将头像上传到阿里云OSS
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度AI检测是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含：抛出异常
        if(!detect) {
            //throw new RuntimeException("没有人脸");
            //抛出自定义的异常
//            ErrorResult result = new ErrorResult();
//            result.setErrCode("00002");
//            result.setErrMessage("上传的头像中没有包含人脸");
            throw new BusinessException(ErrorResult.faceError());
        }
        //2.2 如果存在，调用API更新
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(imageUrl);
        userInfoApi.update(userInfo);
    }

    //根据id查询
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);  //将对象1的同名，同类型属性，自动copy到对象2中
        vo.setAge(userInfo.getAge() == null ?"18":userInfo.getAge().toString());
        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }


    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * 参数：
     *    地址参数：type
     *          1 互相关注
     *          2 我关注
     *          3 粉丝
     *          4 谁看过我
     *    page，pagesize
     * 返回值：
     *    PageResult<UserLikeListVo>
     */
    public PageResult friends(Integer type, Integer page, Integer pagesize) {
        if(type != 4) {
            //实战中的查询
            return new PageResult();
        }
        //1、调用API根据用户id查询：List<Visitors>
        List<Visitors> list = visitorsApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        //2、将List<Visitors>转化为 List<UserLikeListVo>
        //3、获取用户id的集合
        List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        //4、查询用户数据
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<UserLikeListVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            UserInfo info = map.get(visitors.getVisitorUserId());
            if(info != null) {
                UserLikeListVo vo = UserLikeListVo.init(info, visitors);
                vos.add(vo);
            }
        }
        String key = Constants.VISITORS_USER;
        String hashKey = UserHolder.getUserId().toString();
        String value = System.currentTimeMillis() + "";
        redisTemplate.opsForHash().put(key,hashKey,value);
        //5、构造返回值
        return new PageResult(page,pagesize,0l,vos);
    }
}
